﻿using System;
using System.Collections.Generic;
using System.IO;
using Seagull.Generic;
using Seagull.Model.Stat;
using System.Linq;

namespace Seagull.DAL.Stat
{
    public class ChannelStatFileReader : IDisposable
    {
        private readonly BinaryReader _binaryReader;

        public ChannelStatFileReader(byte channel)
            : this(FileHelper.Open(PathHelper.GetChannelStatFile(channel).OpenRead))
        {
        }

        public ChannelStatFileReader(Stream stream)
        {
            _binaryReader = new BinaryReader(stream);
        }

        public ChannelStatistics ReadAllAfter(DateTime startTime)
        {
            if(_binaryReader.BaseStream.AtEnd())
            {
                return new ChannelStatistics();
            }
            var statFileStartTime = TimestampAccessor.Read(_binaryReader);
            if(startTime > statFileStartTime)
            {
                // 需要跳过一些数据
                var hours = (int)(startTime - statFileStartTime).TotalHours;
                var bytesToSkip = hours * 2;
                _binaryReader.BaseStream.Seek(bytesToSkip, SeekOrigin.Current);
            }
            return new ChannelStatistics(statFileStartTime, ReadStatistics().ToArray());
        }

        private IEnumerable<Statistic> ReadStatistics()
        {
            while(!_binaryReader.BaseStream.AtEnd())
            {
                var max = _binaryReader.ReadByte();
                var avg = _binaryReader.ReadByte();
                yield return new Statistic(max, avg);
            }
        }

        public void Dispose()
        {
            if (_binaryReader != null)
            {
                _binaryReader.Dispose();
            }
        }
    }
}
